<?php
namespace Wap\Model;
use Think\Model;

class EventModel extends Model
{
    protected $_validate = array();

    //点赞+1
    public function praiseInc( $event, $organiztion, $openid )
    {
        $conditions = array(
            'id' => $organiztion,
            'event_id' => $event
        );

        $data = array(
            'event_id' => $event,
            'openid' => $openid,
            'update_time' => time(),
            'organiztion_id' => $organiztion
        );

        $this->startTrans();
        $added = M( 'organiztion_record' )->add( $data );
        if( !$added )
        {
            $this->rollback();
            $praise = false;
            return $praise;
        }

        $praised = M( 'organiztion' )
            ->where( $conditions )
            ->setInc( 'praise', 1 );
        if( !$praised ){
            $this->rollback();
            $praise = false;
            return $praise;
        }else{
            $this->commit();
        }

        return $praised;
    }

    //score
    public function scoreInc( $event, $event_item, $organiztion, $score )
    {
        $conditions = array(
            'item_id' => $event_item,
            'organiztion_id' => $organiztion
        );

        $scored = M( 'organiztion_item' )
            ->where( $conditions )
            ->find();

        if( $scored )
        {
            return false;
        }

        $conditions = array(
            'id' => $organiztion,
            'event_id' => $event
        );

        $this->startTrans();
        $scored = M( 'organiztion' )
            ->where( $conditions )
            ->setInc( 'score', $score );

        if( $scored === false )
        {
             $this->rollback();
             return false;
        }

        $datas = array(
            'item_id' => $event_item,
            'organiztion_id' => $organiztion,
            'score' => $score
        );

        $scored = M( 'organiztion_item' )->add( $datas );

        if( !$scored ){
            $this->rollback();
            return false;
        }else{
             $this->commit();
        }

        return true;
    }

    public function rank( $organiztion )
    {
        $conditions = array(
            'esm_organiztion.id' => $organiztion
        );

        $result = M( 'organiztion' )
            ->where( $conditions )
            ->find();

        if( !isset( $result['event_id'] ) )
        {
             return $result;
        }

        $conditions = array(
            'event_id' => $result['event_id'],
            'score' => array( 'gt', $result['score'] )
        );

        $rank = M( 'organiztion' )
            ->where( $conditions )
            ->count();

        $result['rank'] = $rank + 1;

        return $result;
    }
}

?>
